/*
 * 版权所有 (C) 2015 知启蒙(ZHIQIM) 保留所有权利。[遇见知启蒙，邂逅框架梦]
 * 
 * https://zhiqim.org/project/zhiqim_framework/zhiqim_kernel.htm
 *
 * Zhiqim Kernel is licensed under Mulan PSL v2.
 * You can use this software according to the terms and conditions of the Mulan PSL v2.
 * You may obtain a copy of Mulan PSL v2 at:
 *          http://license.coscl.org.cn/MulanPSL2
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PSL v2 for more details.
 */
package org.zhiqim.kernel.httpclient;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;

import org.zhiqim.kernel.util.Bytes;
import org.zhiqim.kernel.util.Streams;
import org.zhiqim.kernel.util.Stringx;
import org.zhiqim.kernel.util.Validates;

/**
 * HTTP/HTTPS POST访问流类，把HttpURLConnection的流转化成ByteArrayInputStream，该类为非文本响应内容时使用
 *
 * @see HttpPost       如果响应为文本请直接使用HttpPost替换
 * @see HttpDownload   大文件下载，请使用HttpDownload替换，以防止内存使用过大
 * @version v1.0.0 @author zouzhigang 2014-3-21 新建与整理
 */
public class HttpPostStream extends HttpClient
{
    private String queryString;
    private String mimeType;
    private String encoding;
    
    private ByteArrayOutputStream in;
    
    public HttpPostStream(String url)
    {
        super(url, _POST_);
        this.mimeType = _APPLICATION_X_WWW_FORM_;
        this.encoding = _UTF_8_;
    }
    
    public HttpPostStream setQueryString(String queryString, String encoding)
    {
        this.queryString = Stringx.trim(queryString);
        this.encoding = Stringx.trim(encoding);
        return this;
    }
    
    public HttpPostStream setQueryString(String queryString, String mimeType, String encoding)
    {
        this.queryString = Stringx.trim(queryString);
        this.mimeType = Stringx.trim(mimeType);
        this.encoding = Stringx.trim(encoding);
        return this;
    }
    
    /** 重写获取HTTP结果 */
    public HttpResult getResult()
    {
        return new HttpResult(responseStatus, responseText, in==null?null:in.toByteArray());
    }
    
    /** 获取输入流 */
    public InputStream getInputStream()
    {
        return new ByteArrayInputStream(in.toByteArray());
    }
    
    /** 获取字节数组 */
    public byte[] getBytes()
    {
        return in.toByteArray();
    }
    
    protected boolean doPreRequestProperty()
    {
        setDoOutput(true);
        if (!hasRequestProperty(_CONTENT_TYPE_))
        {//没有设置ContentType的才设置
            setRequestProperty(_CONTENT_TYPE_, mimeType + "; charset="+encoding);
        }
        setRequestProperty(_CONTENT_LENGTH_, Bytes.getByteLen(queryString, encoding));
        return true;
    }
    
    protected void doWriteRequestContent(HttpURLConnection conn) throws IOException
    {//默认需要打开输出流
        if (Validates.isEmpty(queryString))
        {//内容为空输出空字节数组
            conn.getOutputStream().write(new byte[0]);
        }
        else
        {//正常内容
            conn.getOutputStream().write(queryString.getBytes(encoding));
        }
    }
    
    protected void doReadResponseContent(HttpURLConnection conn) throws IOException
    {
        if (responseStatus == _302_FOUND_)
        {//重定向
            responseText = conn.getHeaderField("Location");
            return;
        }
        
        if (responseStatus != _200_OK_)
        {//错误
            responseText = getResponseError(conn);
            return;
        }
        
        //成功
        in = new ByteArrayOutputStream();
        try(InputStream input = conn.getInputStream())
        {
            Streams.putBytes(input, in);
        }
        
        responseText = "调用成功";
    }
}
